import {defineStore} from "pinia";
import {ref} from "vue";
import type {RouteRecordRaw} from "vue-router";
import router from "@/router";
import pinia from "@/stores";

export const useTabsBarStore = defineStore({
    // id: 必须的，在所有 Store 中唯一
    id: 'app-tabsBar',
    // state: 返回对象的函数
    state: (): {
        activeTabsValue: string
        visitedViews: RouteRecordRaw[]
        cachedViews: any[]
    } => ({
        activeTabsValue: '/index',
        visitedViews: [], // 选中过的路由表
        cachedViews: [], // 使用 keepAlive 时的缓存
    }),
    getters: {},
    // 可以同步 也可以异步
    actions: {
        setTabsMenuValue(val: string) {
            this.activeTabsValue = val
        },
        addView(view: RouteRecordRaw) {
            this.addVisitedView(view)
        },
        removeView(routes: RouteRecordRaw[]) {
            return new Promise((resolve) => {
                this.visitedViews = this.visitedViews.filter(
                    (item) => !routes.includes((item as any).path),
                )
                resolve(null)
            })
        },
        addVisitedView(view: RouteRecordRaw) {
            this.setTabsMenuValue(view.path)
            if (this.visitedViews.some((v) => v.path === view.path) || !view.meta)
                return
            this.visitedViews.push(
                Object.assign({}, view, {
                    title: view.meta.title || 'no-name',
                }),
            )

            if (view.meta.keepAlive && view.name) {
                this.cachedViews.push(view.name)
            }
        },
        delView(activeTabPath: any) {
            return new Promise((resolve) => {
                this.delVisitedView(activeTabPath)
                this.delCachedView(activeTabPath)
                resolve({
                    visitedViews: [...this.visitedViews],
                    cachedViews: [...this.cachedViews],
                })
            })
        },
        toLastView(activeTabPath: string) {
            const index = this.visitedViews.findIndex(
                (item) => item.path === activeTabPath,
            )
            const nextTab =
                this.visitedViews[index + 1] || this.visitedViews[index - 1]
            if (!nextTab) return
            router.push(nextTab.path)
            this.addVisitedView(nextTab)
        },
        delVisitedView(path: string) {
            return new Promise((resolve) => {
                this.visitedViews = this.visitedViews.filter((v) => {
                    if (!v.meta) return
                    return v.path !== path || v.meta.affix
                })
                this.cachedViews = this.cachedViews.filter((v) => {
                    return v.path !== path || v.meta.affix
                })
                resolve([...this.visitedViews])
            })
        },
        delCachedView(view: RouteRecordRaw) {
            return new Promise((resolve) => {
                const index = this.cachedViews.indexOf(view.name)
                index > -1 && this.cachedViews.splice(index, 1)
                resolve([...this.cachedViews])
            })
        },
        clearVisitedView() {
            this.delAllViews()
        },
        delAllViews() {
            this.visitedViews = this.visitedViews.filter(
                (v) => v.meta && v.meta.affix,
            )
            this.cachedViews = this.visitedViews.filter((v) => v.meta && v.meta.affix)
        },
        delOtherViews(path: string) {
            this.visitedViews = this.visitedViews.filter((item) => {
                return item.path === path || (item.meta && item.meta.affix)
            })
            this.cachedViews = this.visitedViews.filter((item) => {
                return item.path === path || (item.meta && item.meta.affix)
            })
        },
        goHome() {
            this.activeTabsValue = '/index'
            router.push({ path: '/index' })
        },
        updateVisitedView(view: RouteRecordRaw) {
            for (let v of this.visitedViews) {
                if (v.path === view.path) {
                    v = Object.assign(v, view)
                    break
                }
            }
        },
    },
})


const useTabsBarStore1 = defineStore('app-tabsbar',
    () => {
        const activeTabsValue = ref('/index')
        const visitedViews = ref([] as RouteRecordRaw[])
        const cachedViews = ref([] as any[])

        const setTabsMenuValue = (val: string) => {
            activeTabsValue.value = val;
        }
        // 添加页面
        const addView = (view: RouteRecordRaw) => {
            addVisitedView(view)
        }
        // 删除页面
        const removeView = (routes: RouteRecordRaw[]) => {
            return new Promise((resolve) =>{
                visitedViews.value = visitedViews.value.filter(
                    (item) => !routes.includes((item as any).path)
                )
                resolve(null)
            })
        }

        const addVisitedView = (view: RouteRecordRaw) => {
            setTabsMenuValue(view.path)

            if (visitedViews.value.some((v) => v.path=== view.path) || !view.meta) {
                return
            }

            visitedViews.value.push(
                Object.assign({}, view, {
                    title: view.meta.title || 'no-name'
                })
            )

            if (view.meta.keepAlive && view.name) {
                cachedViews.value.push(view.name)
            }
        }

        const delView =  (activeTabPath: any)=> {
            return new Promise(async (resolve) => {
                const arr_visited = await delVisitedView(activeTabPath) as any[]
                const arr_cached = await delCachedView(activeTabPath) as any[]
                resolve({
                    visitedViews: [...arr_visited],
                    cachedViews: [...arr_cached]
                })
            })
        }

        const toLastView = async (activeTabPath: string) => {
            const index = visitedViews.value.findIndex(
                (item) => item.path === activeTabPath
            )

            const nextTab = visitedViews.value[index + 1] || visitedViews.value[index -1]
            if (!nextTab) return
            await router.push(nextTab.path)
            addVisitedView(nextTab)
        }

        const delVisitedView = (path: string) => {
            return new Promise((resolve) => {
                visitedViews.value = visitedViews.value.filter((v) => {
                    if (!v.meta) return
                    return v.path !== path || v.meta.affix;
                })

                cachedViews.value = cachedViews.value.filter((v) => {
                    return v.path !== path || v.meta.affix
                })

                resolve([...visitedViews.value])
            })
        }

        const delCachedView = (view : RouteRecordRaw)=>{
            return new Promise((resolve) => {
                const index = cachedViews.value.indexOf(view.name)
                index > -1 && cachedViews.value.splice(index, 1)
                resolve([...cachedViews.value])
            })
        }

        const clearVisitedView = ()=>{
            delAllViews()
        }

        const delAllViews = () => {
            visitedViews.value = visitedViews.value.filter(
                (v)=> v.meta && v.meta.affix
            )
            cachedViews.value = visitedViews.value.filter((v) => {
               return  v.meta && v.meta.affix
            })
        }

        const delOtherViews = (path: string) => {
            visitedViews.value = visitedViews.value.filter((item) => {
                return item.path === path || (item.meta && item.meta.affix)
            })

            cachedViews.value = visitedViews.value.filter((item) => {
                return item.path === path || (item.meta && item.meta.affix)
            })
        }

        const goHome = ()=>{
            activeTabsValue.value = '/index'
            router.push({ path:'/index' })
        }

        const unpdateVisitedView = (view: RouteRecordRaw) => {
            for (let v of visitedViews.value){
                if (v.path === view.path) {
                    v = Object.assign(v, view)
                    break
                }
            }
        }

        return {
            activeTabsValue, visitedViews, cachedViews,
            addView,
            removeView,
            addVisitedView,
            goHome,
            delOtherViews,
            delAllViews,
            clearVisitedView,
            delCachedView,
            delVisitedView,
            unpdateVisitedView,
            delView,
            toLastView,
            setTabsMenuValue
        }
    },{
        persist: {
            // enabled: false
            // strategies: [{
            //     // 自定义存储的 key，默认是 store.$id
            //     key: "custom storageKey",
            //     // 可以指定任何 extends Storage 的实例，默认是 sessionStorage
            //     storage: localStorage,
            //     // state 中的字段名，按组打包储存
            //     paths: ["foo", "bar"]
            // }],
        }
})

export const useTabsBarStoreWithOut = () => {
    return useTabsBarStore(pinia)
}